define([
  'jquery',
  'jqueryui',
  'underscore',
  'backbone',
  'models/setting/SettingModel',
  'text!templates/settings/settingsTemplate.html',
  'msgbox',
  'multiselect'
], function($,JQueryUI, _, Backbone, SettingModel, settingsTemplate,MsgBox,Multiselect){

  var SettingView = Backbone.View.extend({
    el: $(".mainpanel"),
    events: {'click #submitdetails' : 'submitButton',
        "change #settingsform :input" :"changedSetting"
        } ,
     model:  new SettingModel(),
    initialize: function(){
    	//_.bindAll(this, "changed");
        var Hospitals = Backbone.Collection.extend({
            model: Backbone.Model.extend({url:'/allHospitals'}),
            url:'/allHospitals'
          });	
        this.allHospitals = new Hospitals();
        var Labs = Backbone.Collection.extend({
            model: Backbone.Model.extend({url:'/allLabs'}),
            url:'/allLabs'
          });	
        this.allLabs = new Labs();
        
    },
    render: function(){
    	
		 //var settingModel = new SettingModel();
		 //this.model = settingModel;
    	var self=this
        var renderApp = _.after(3, function(){
            var data = {
          		  setting: self.model,
          		  allHospitals:self.allHospitals.models,
          		  allLabs: self.allLabs.models,
          	        _: _ 
          	      };
    	      self.loadTemplate(data);

        });


    	this.allHospitals.fetch({success: renderApp});
    	this.allLabs.fetch({success: renderApp});
    	this.model.fetch({success: renderApp});

    },
    loadTemplate: function(data){
 	      var compiledTemplate = _.template( settingsTemplate, data );
  	      this.$el.html(compiledTemplate);
  	      $(".select").multiselect({
  	    	  multiple: false,
  	  		   header: "Select an option",
  	  		   noneSelectedText: "Select an Option",
  	  		   selectedList: 1
  	    	});
  	    if(data.setting.get('user').userType == 'D'){
  	  	    $("#hospitals").multiselect({
	  	    	noneSelectedText: "Hospitals"
	  	    	}).multiselectfilter();
  	    	
  	    }
  	    if(data.setting.get('user').userType == 'L'){
  	  	    $("#labs").multiselect({
	  	    	noneSelectedText: "Labs",
	  	    	multiple: false,
  	  		   selectedList: 1
  	    	}).multiselectfilter();
  	    	
  	    }
  	    if(!data.setting.get('user').userType){
  	  	    $("#hospitals").multiselect({
	  	    	noneSelectedText: "Hospitals"
	  	    	}).multiselectfilter();

  	  	    $("#labs").multiselect({
	  	    	noneSelectedText: "Labs",
	  	    	multiple: false,
	  	    	selectedList: 1
  	    	}).multiselectfilter();
   			$(".hdoctor").addClass("dnone");
   	   		$(".hpatient").addClass("pnone");
   	   		$(".hlab").addClass("hnone");
   	   		$("#hospitals").multiselect('hide');
   	   		$("#labs").multiselect('hide');

  	    }
  	    
  	      var self=this;
	      $("input#speciality").autocomplete({
	    	    source: function(request,response){
	    			 $.ajax({
	    			        type: "GET",
	    			        url: "/getSpeciality?keyword=&term="+$("#speciality").val(),
	    			        success: function(data){
	    			              response($.map(data, function(item) {
	    			                    return { 
	    			                        label: item.speciality,
	    			                        value: item.speciality
	    			                        };
	    			                    }));
	    			        }
	    		    });
	    	    },
	    	    minLength: 0,
	    	    select: function(e,ui){
	    	        var value = $("#speciality").val();
	    	        var obj = "{\"speciality\":\""+ui.item.value+"\"}";
	    	        var objInst = JSON.parse(obj);
	    	        self.model.set(objInst);
	    	    }
	    	}).focus(function () {
	    	    $(this).autocomplete("search");
	    	});
  	
  },
    close: function(){
    	
    },
    submitButton: function(){
    	if(!this.model.get("submitted") || this.model.get("submitted") == false){
    		var obj = "{\"submitted\":\"true\"}";
            var objInst = JSON.parse(obj);
            this.model.set(objInst);
    	}else{
        	return;
    	}
/*        var usertype = $("#userType").val();
    	var usertypejson= {
    			usertypes: usertype
    		};
        this.model.set(JSON.parse(JSON.stringify( usertypejson)));
*/
        
    	var error =false;
		$(".error").text("")

    	if(null== this.model.get("user").email && (!this.model.get("emailid") || this.model.get("emailid")=="")){
    		$("#errorMsgemailid").text("Email Id cannot be blank.")
    		error=true;
    	}
       	if(null== this.model.get("user").phoneNumber && (!this.model.get("phonenumber") || this.model.get("phonenumber")=="")){
    		$("#errorMsgphonenumber").text("Phone Number cannot be blank.")
    		error=true;
       	}
       	if(null== this.model.get("user").userType && (!this.model.get("userType") || this.model.get("userType")=="")){
    		$("#errorMsgRole").text("User Role cannot be blank.")
    		error=true;
       	}
       	if(this.model.get("userType")=="D"){
       		if(!this.model.get("speciality") || this.model.get("speciality")==""){
       	   		$("#errorMsgSpeciality").text("Speciality cannot be blank.")
        		error=true;
       		}
       		if(!this.model.get("registrationNo") || this.model.get("registrationNo")==""){
       	   		$("#errorMsgregistration").text("Registration Number cannot be blank.")
        		error=true;
       		}
       	}
       	
       	if(!error){
       		var self=this;
       	if(!$("#usertype").val()){
       		$("#usertype").val(this.model.get("userType"));	
       	}
       	if($("#usertype").val()== 'D' && this.model.get("hospitals") !=null)
       		this.model.set("hospitals",JSON.parse("["+this.model.get("hospitals")+"]"));
       	console.log(this.model);
       	if($("#usertype").val()== 'L')
       		this.model.set("labId",$("#labs").val());
  
	       	this.model.save(null, {
	    		    success: function (model, response) {
	   	      		 $.msgBox({
						    title:"Appment",
						    content:"Successfully Saved!",
						    type:"info",
						    success: function (result) {window.location.hash = "activity";}
						});
	
	    		    },
	    		    error: function (model, response) {
	    		        console.log("error");
	    		    }
	    		});
       	}else{
       		this.model.set("submitted",false);
       	}
    },
    changedSetting:function(evt) {
    	//console.log(evt);   
       var changed = evt.currentTarget;
       var value = $("#"+changed.id).val();
   	if(changed.id== "userType"){
   		if(value=="P"){
   			$(".hdoctor").addClass("dnone");
   	   		$(".hpatient").removeClass("pnone");
   	   		$(".hlab").addClass("hnone");
   	   		$("#hospitals").multiselect('hide');
   	   		$("#labs").multiselect('hide');
   		}else if(value=="D"){
   			$(".hpatient").addClass("pnone");
   			$(".hlab").addClass("hnone");
   	   		$(".hdoctor").removeClass("dnone");  	  	    
   	   		$("#hospitals").multiselect('show');
   	   		$("#labs").multiselect('hide');

   		}else if(value=="L"){
   			$(".hdoctor").addClass("dnone");
   			$(".hlab").removeClass("hnone");
   			$(".hpatient").addClass("pnone");
  	   		$("#hospitals").multiselect('hide');
  	   		$("#labs").multiselect('show');
   		}else{
   			$(".hdoctor").addClass("dnone");
   			$(".hpatient").addClass("pnone")
   			$(".hlab").addClass("hnone");;
   	   	   	$("#hospitals").multiselect('hide');
   	   	   	$("#labs").multiselect('hide');
   		}
   	}
       var obj = "{\""+changed.id +"\":\""+value+"\"}";
       var objInst = JSON.parse(obj);
		 //console.log(this.model);
		 
       this.model.set(objInst);
    }

  });

  return SettingView;
});
